package cn.stylefeng.guns.modular.miniapp.controller;

import org.slf4j.*;
import javax.servlet.http.*;
import cn.stylefeng.guns.modular.miniapp.config.*;
import org.springframework.web.multipart.commons.*;
import com.google.common.collect.*;
import com.google.common.io.*;
import java.io.*;
import cn.binarywang.wx.miniapp.api.*;
import java.util.*;
import org.springframework.web.multipart.*;
import me.chanjar.weixin.common.bean.result.*;
import me.chanjar.weixin.common.error.*;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping({ "/wx/media/{appid}" })
public class WxMaMediaController
{
    private final Logger logger;
    
    public WxMaMediaController() {
        this.logger = LoggerFactory.getLogger((Class)this.getClass());
    }
    
    @PostMapping({ "/upload" })
    public List<String> uploadMedia(@PathVariable final String appid, final HttpServletRequest request) throws WxErrorException {
        final WxMaService wxService = WxMaConfiguration.getMaService(appid);
        final CommonsMultipartResolver resolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        if (!resolver.isMultipart(request)) {
            return Lists.newArrayList();
        }
        final MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;
        final Iterator<String> it = (Iterator<String>)multiRequest.getFileNames();
        final List<String> result = Lists.newArrayList();
        while (it.hasNext()) {
            try {
                final MultipartFile file = multiRequest.getFile((String)it.next());
                final File newFile = new File(Files.createTempDir(), file.getOriginalFilename());
                this.logger.info("filePath is \uff1a" + newFile.toString());
                file.transferTo(newFile);
                final WxMediaUploadResult uploadResult = wxService.getMediaService().uploadMedia("image", newFile);
                this.logger.info("media_id \uff1a " + uploadResult.getMediaId());
                result.add(uploadResult.getMediaId());
            }
            catch (IOException e) {
                this.logger.error(e.getMessage(), (Throwable)e);
            }
        }
        return result;
    }
    
    @GetMapping({ "/download/{mediaId}" })
    public File getMedia(@PathVariable final String appid, @PathVariable final String mediaId) throws WxErrorException {
        final WxMaService wxService = WxMaConfiguration.getMaService(appid);
        return wxService.getMediaService().getMedia(mediaId);
    }
}
